<?php

namespace api\modules\shop\controllers;

use common\models\Tree;

use common\service\ConstantService;
use common\service\GlobalUrlService;

class TreeController extends ShopBaseController
{

    /**
     * 分类
     */
    public function actionGetTree(){
        $pid = $this->get('pid')?$this->get('pid'):0;

        if($pid == 0){
            $data['tree'] = $this->_GetTreeInfo($pid);
            $data['list'] = $this->_GetTreeInfo($data['tree'][0]['id']);
        } else {
            $data['list'] = $this->_GetTreeInfo($pid);
        }
        return $this->renderJson($data,'',ConstantService::$response_success);
    }

    private function _GetTreeInfo($pid = 0){
        $treeDb = Tree::find();
        $treeDb->andWhere(['pid'=>$pid]);
        $treeDb->select('id,tree_name,pid,icon');
        $TreeData = $treeDb->asArray()->all();
        if($pid > 0){
            $ids = array_column($TreeData,'id');
            $treeDb = Tree::find();
            $treeDb->select('id,tree_name,pid,icon');
            $treeDb->andWhere(['pid'=>$ids]);
            $SonTree = $treeDb->asArray()->all();
            $NewTreeData = [];
            foreach ($SonTree as $val){
                $val['icon'] = $val['icon']?GlobalUrlService::buildCdnUrl($val['icon']):'';
                $NewTreeData[$val['pid']][] = $val;
            }
            unset($val);
            $result = [];
            foreach ($TreeData as $val){
                $Temp = $val;
                $Temp['list'] = $NewTreeData[$val['id']];
                $result[] = $Temp;
            }
            $TreeData = $result;
        }

        return $TreeData;
    }
}